import { troggleActive } from "../../js/common.js"
import { Select } from '/static/js/gd-ui/select/index.es.js'
import CONSTS from '/static/js/list/mobile/const.js'
import ButtonGroup from '/static/js/gd-ui/button/group.es.js'

class CommonRank {
    constructor() {
        this.rankList = () => {}
        this.fgDate = {}
        this.dateType = 0
        this.dateUrl = ''
        this.exportUrl = ''
        this.rankUrl = ''
    }
    initRender() {
        this.initOption()
        this.initEvent()
        if(!gugeeGobal.isMobile) {
            this.initPagination()
        }
    }
    initOption() {
        _axios.get(this.dateUrl).then(res => {
            if (res.Code === 200) {
                this.fgDate = res.Data
                if(gugeeGobal.isMobile) {
                    const sortDateDay = document.getElementById('sortDateDay')
                    this._initDateOption(sortDateDay, this.fgDate.dailyDate, true)

                    const sortDateWeek = document.getElementById('sortDateWeek')
                    this._initDateOption(sortDateWeek, this.fgDate.weeklyDate)

                    const sortDateMonth = document.getElementById('sortDateMonth')
                    this._initDateOption(sortDateMonth, this.fgDate.monthlyDate)

                    let gdMobileSelect = new Select()
                    if(gugeeGobal.isLogin) {
                        gdMobileSelect.setBeforeSelectEvent(e => {
                            if(e.target.classList.contains('rank-tab-select')) {
                                return true
                            }
                            toLogin()
                            return false
                        })
                    }
                    gdMobileSelect.init()
                } else {
                    const dateDayList = document.getElementById('dateDayList')
                    this._initDateOption(dateDayList, this.fgDate.dailyDate, true)

                    const dateWeekList = document.getElementById('dateWeekList')
                    this._initDateOption(dateWeekList, this.fgDate.weeklyDate)

                    const dateMonthList = document.getElementById('dateMonthList')
                    this._initDateOption(dateMonthList, this.fgDate.monthlyDate)

                    let gdSelect = new Select()
                    gdSelect.setElement(document.querySelectorAll('.export-row .gd-select'))
                    if(!gugeeGobal.isLogin) {
                        gdSelect.setBeforeSelectEvent(() => {
                            toLogin()
                            return false
                        })
                    }
                    gdSelect.setSelectedEvent(e => {
                        const value = e.target.getAttribute('value')
                        params.page = 1
                        params.date = value
                        this.getRankList()
                    })
                    gdSelect.init()
                }
            }
            document.querySelectorAll('.filter-wrap__inner>ul>li').forEach(item => {
                item.addEventListener('click', event => {
                    const element = event.target
                    troggleActive(element, () => {
                        params.page = 1
                        const value = element.getAttribute('value')
                        const ul = element.parentElement
                        const oldActive = ul.querySelector('.is-active')
                        oldActive.innerHTML = oldActive.innerText
                        if(ul.id === 'sortCategory') {
                            showLoading()
                            window.location.href = value ?'/instagram/' + value + '-' + this.rankUrl :'/instagram/' + this.rankUrl
                        } else {
                            params.date = value
                            element.innerHTML = element.getAttribute('data-label') + '<div class="right"> <i class="iconfont iconzhichi"></i></div>'
                            document.querySelectorAll('.sort-list .sort-item:nth-child(2)').forEach(sortItem => {
                                sortItem.innerHTML = element.getAttribute('data-label') + '<i class="iconfont icondown1"></i>'
                            })
                            this.getRankList()
                        }
                        this.hideFilter()
                    })
                })
            })
        })
    }
    initEvent() {
        if(gugeeGobal.isMobile) {
            if(gugeeGobal.isLogin) {
                let scrollTimer
                window.addEventListener('scroll', () => {
                    if (!hasData) {
                        return
                    }
                    if (parseInt((getScrollTop() + getWindowHeight() + 200)) >= getScrollHeight()) {
                        if (scrollTimer) {
                            clearTimeout(scrollTimer)
                        }
                        scrollTimer = setTimeout(() => {
                            const list_len = document.querySelectorAll('.gd-mobile-list__wrap > a').length
                            if (list_len >= params.page * 10) {
                                params.page++
                                this.getRankList()
                            }
                        }, 500)
                    } else {
                        if (scrollTimer) {
                            clearTimeout(scrollTimer)
                        }
                    }
                })
            }
            document.querySelectorAll('.gd-btn-select .btn-select-item').forEach(item => {
                item.addEventListener('click', e => {
                    const element = e.target
                    troggleActive(element , () => {
                        params.page = 1
                        const ranType = +e.target.getAttribute('value')
                        if(params['rankType'] !== ranType) {
                            let str = ''
                            let dateName = ''
                            params['rankType'] = ranType
                            if(ranType === 0) {
                                // visitRecode(17)
                                dateName = 'Daily'
                                if(this.fgDate.dailyDate.length > 0) {
                                    params.date = this.fgDate.dailyDate[0].dateCode
                                    str = this.fgDate.dailyDate[0].dateDesc + '<i class="iconfont icondown1"></i>'
                                } else {
                                    params.date = ''
                                }
                            } else if(ranType === 1) {
                                // visitRecode(18)
                                dateName = 'Weekly'
                                if(this.fgDate.weeklyDate.length > 0) {
                                    params.date = this.fgDate.weeklyDate[0].dateCode
                                    str = this.fgDate.weeklyDate[0].dateDesc + '<i class="iconfont icondown1"></i>'
                                } else {
                                    params.date = ''
                                }
                            } else {
                                // visitRecode(19)
                                dateName = 'Monthly'
                                if(this.fgDate.monthlyDate.length > 0) {
                                    params.date = this.fgDate.monthlyDate[0].dateCode
                                    str = this.fgDate.monthlyDate[0].dateDesc + '<i class="iconfont icondown1"></i>'
                                } else {
                                    params.date = ''
                                }
                            }
                            document.querySelectorAll('.sort-list .sort-item:nth-child(1)').forEach(item => {
                                item.innerHTML = dateName + '<i class="iconfont icondown1"></i>'
                            })
                            document.querySelectorAll('.sort-list .sort-item:nth-child(2)').forEach(item => {
                                item.innerHTML = str
                            })
                        }
                        this.hideFilter()
                        this.getRankList()
                    })
                })
            })
            document.querySelectorAll('.sort-list').forEach(sortList => {
                const items = sortList.querySelectorAll('.sort-item')
                items.forEach((sortItem,i) => {
                    sortItem.addEventListener('click', () => {
                        this.showFilter(i)
                    })
                })
            })
            document.querySelector('.filter-wrap__inner').addEventListener('click', e => {
                e.stopPropagation()
            })
            document.querySelector('.filter-wrap').addEventListener('click', () => {
                this.hideFilter()
            })

            const viewMoreEle = document.querySelector(' .link-login')
            viewMoreEle && viewMoreEle.addEventListener('click', () => {
                toLogin()
            })
        } else {
            const dateDayList = document.getElementById('dateDayList')
            const dateWeekList = document.getElementById('dateWeekList')
            const dateMonthList = document.getElementById('dateMonthList')
            const label = document.querySelector('.export-row .gd-select .label')
            document.querySelectorAll('.search-wrap li').forEach(item => {
                item.addEventListener('click', e => {
                    if(!gugeeGobal.isLogin) {
                        toLogin()
                        return false
                    }

                    if(!e.target.classList.contains('is-active')) {
                        const value = e.target.getAttribute('value')
                        window.location.href = value ?'/instagram/' + value + '-' +  this.rankUrl :'/instagram/' + this.rankUrl
                    }
                })
            })

            // 选择 周/月
            const buttonGroup = new ButtonGroup()
            buttonGroup.setBeforeSelectedEvent(() => {
                if(!gugeeGobal.isLogin) {
                    toLogin()
                    return false
                }
            })
            buttonGroup.setSelectedEvent((event, i) => {
                params.rankType = i
                if(i === 0) {
                    // visitRecode(17)
                    if(this.fgDate.dailyDate.length > 0) {
                        params.date = this.fgDate.dailyDate[0].dateCode
                        label.innerText = this.fgDate.dailyDate[0].dateDesc
                    } else {
                        label.innerText = ''
                        params.date = undefined
                    }
                    dateDayList.show()
                    dateWeekList.hide()
                    dateMonthList.hide()
                } else if(i === 1) {
                    // visitRecode(18)
                    if(this.fgDate.weeklyDate.length > 0) {
                        params.date = this.fgDate.weeklyDate[0].dateCode
                        label.innerText = this.fgDate.weeklyDate[0].dateDesc
                    } else {
                        label.innerText = ''
                        params.date = undefined
                    }
                    dateDayList.hide()
                    dateWeekList.show()
                    dateMonthList.hide()
                } else {
                    // visitRecode(19)
                    if(this.fgDate.monthlyDate.length > 0) {
                        params.date = this.fgDate.monthlyDate[0].dateCode
                        label.innerText = this.fgDate.monthlyDate[0].dateDesc
                    } else {
                        label.innerText = ''
                        params.date = undefined
                    }
                    dateDayList.hide()
                    dateWeekList.hide()
                    dateMonthList.show()
                }
                params.page = 1
                this.getRankList()
            })
            buttonGroup.init()
            //导出
            document.getElementById('exportBtn').addEventListener('click', () => {
                this.exportRank()
            })
        }
    }
    hideFilter() {
        document.body.style.overflow = 'auto'
        document.body.style.position = 'initial'
        document.querySelector('.filter-wrap').hide()
    }
    showFilter (type) {
        if(!gugeeGobal.isLogin) {
            toLogin()
            return false
        }

        document.body.style.overflow = 'hidden'
        document.body.style.position = 'fixed'
        const filterWrap = document.querySelector('.filter-wrap')
        filterWrap.style.top = getScroll().top + 60 + 'px'
        filterWrap.show()
        document.querySelectorAll('.filter-wrap__inner > ul').forEach(item => {
            item.hide()
        })
        const sortDateType = document.getElementById('sortDateType')
        const sortCategory = document.getElementById('sortCategory')
        if(type === 0) {
            sortDateType.show()
        } else if(type === 1) {
            if(params.rankType === 0) {
                document.getElementById('sortDateDay').show()
            } else if(params.rankType === 1) {
                document.getElementById('sortDateWeek').show()
            } else {
                document.getElementById('sortDateMonth').show()
            }
        } else {
            sortCategory.show()
        }
    }
    getRankList() {
       this.rankList()
    }
    getList(wrap,url, listFn, loadedFn) {
        _axios.get(url).then(res => {
            if (res.Code === 200) {
                const list = res.Data.list
                let str = ''
                if (gugeeGobal.isMobile) {
                    const rorate = document.querySelector('.gd-mobile-list__footer .rotate')
                    const footerText = document.querySelector('.gd-mobile-list__footer .list-footer-tx')
                    if (res.Data.totalRow === 0) {
                        wrap.innerHTML = ''
                        showNoDataImg(wrap)
                        rorate && rorate.hide()
                        footerText && footerText.hide()
                        hasData = false
                        if (!gugeeGobal.isLogin) {
                            document.querySelector('.gd-mobile-list__footer').hide()
                        }
                        wrap.removeAttribute('style')
                    } else {
                        if (!gugeeGobal.isLogin) {
                            document.querySelector('.gd-mobile-list__footer').show()
                        }
                        if (res.Data.lastPage) {
                            hasData = false
                            rorate && rorate.hide()
                            footerText && (() => {
                                footerText.innerHTML = CONSTS.LIST_FOOTER_END
                                footerText.show()
                            })()
                            wrap.style.minHeight = 'auto'
                        } else {
                            hasData = true
                            rorate && rorate.show()
                            footerText && footerText.hide()
                        }
                        str += listFn(list)

                        if (params.page === 1) {
                            wrap.innerHTML = str
                        } else {
                            wrap.innerHTML = wrap.innerHTML + str
                        }
                        loadedFn && loadedFn()
                    }
                } else {
                    if (params.page === 1) {
                        totalRow = res.Data.totalRow
                        this.initPagination()
                    }
                    if (res.Data.totalRow === 0) {
                        showNoDataImg(wrap, {
                            isTable: true
                        })
                    } else {
                        wrap.innerHTML = listFn(list)
                        loadedFn && loadedFn()
                        initPopover()
                        /*if(!gugeeGobal.isLogin || (gugeeGobal.isLogin && gugeeGobal.roleId < 3)) {
                            document.querySelectorAll('.td-audience').forEach(item => {
                                showLock(item, {
                                    roleId: 3
                                })
                            })
                        }*/
                    }
                }
            } else if (res.Code === 403) {
                if (gugeeGobal.isMobile) {
                    const rorate = document.querySelector('.gd-mobile-list__footer .rotate')
                    const footerText = document.querySelector('.gd-mobile-list__footer .list-footer-tx')
                    rorate.hide()
                    footerText.innerHTML = res.Msg
                    footerText.show()
                    hasData = false

                    const upgradeEle = document.querySelector('.list-footer-tx .text-link')
                    upgradeEle.addEventListener('click', () => {
                        window.location.href = '/pricing?refer=' + window.location.href
                    })
                }
            }
            wrap.hideLoading()
        })
    }
    initPagination() {
        layui.use('laypage', () => {
            let laypage = layui.laypage;
            //执行一个laypage实例
            laypage.render({
                elem: 'pagination',
                count: totalRow, //数据总数，从服务端得到
                prev: '<i class="iconfont iconicon_previous"></i>',
                next: '<i class="iconfont iconarrowright"></i>',
                jump: (obj, first) => {
                    if (!first) {
                        if(!gugeeGobal.isLogin) {
                            toLogin()
                            return false
                        }
                        params.page = obj.curr
                        this.getRankList()
                    }
                }
            })
        })
    }
    exportRank () {
        if(!gugeeGobal.isLogin) {
            toLogin()
            return false
        }
        const url = getEncodeUrl(this.exportUrl, params)
        window.open(url)
    }
    _initDateOption(element, dateArray, isActive) {
        let str = ''
        if(gugeeGobal.isMobile) {
            dateArray.forEach((item, i) => {
                if(i === 0) {
                    if(isActive) {
                        let title = item.dateDesc + '<i class="iconfont icondown1"></i>'
                        document.querySelectorAll('.is-mobile .sort-list .sort-item:nth-child(2)').forEach(item => {
                            item.innerHTML = title
                        })
                        params.date = item.dateCode
                    }
                    str += '<li data-label="' + item.dateDesc + '" value="' + item.dateCode + '" class="is-active">' +
                        item.dateDesc + '<div class="right"> <i class="iconfont iconzhichi"></i></div></li>'
                } else {
                    str += '<li data-label="' + item.dateDesc + '" value="' + item.dateCode + '">' + item.dateDesc + '</li>'
                }
            })
        } else {
            dateArray.forEach((item,i) => {
                str += '<li value="' + item.dateCode + '"'
                if(i === 0) {
                    str += ' class="is-active">' + item.dateDesc + '</li>'
                    if(isActive) {
                        element.parentElement.parentElement.querySelector('.label').innerText = item.dateDesc
                        params.date = item.dateCode
                    }
                } else {
                    str += '>' + item.dateDesc + '</li>'
                }
            })
        }
        element.innerHTML = str
    }
    setRankUrl(url) {
        this.rankUrl = url
    }
    setExportUrl (url) {
        this.exportUrl = url
    }
    setDateUrl(url) {
        this.dateUrl = url
    }
    setRankList(fnc) {
        this.rankList = fnc
    }
}
export default CommonRank